package com.hyt.it.ogt.ykcj.service.grade.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.ykcj.common.constant.Constants;
import com.hyt.it.ogt.ykcj.common.enums.BizErrorCode;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.enums.ExamFormEnums;
import com.hyt.it.ogt.ykcj.common.enums.ExchangeValTypeEnum;
import com.hyt.it.ogt.ykcj.common.enums.zs.CertificateGrantObjectEnums;
import com.hyt.it.ogt.ykcj.common.enums.zs.CertificateProvideStatusEnums;
import com.hyt.it.ogt.ykcj.common.enums.zs.CertificateStatusEnums;
import com.hyt.it.ogt.ykcj.common.enums.zs.IdentificationType;
import com.hyt.it.ogt.ykcj.common.exception.CustomException;
import com.hyt.it.ogt.ykcj.common.utils.DateUtils;
import com.hyt.it.ogt.ykcj.common.utils.IdUtils;
import com.hyt.it.ogt.ykcj.common.utils.bean.BeanUtils;
import com.hyt.it.ogt.ykcj.domain.exam.ExamInfo;
import com.hyt.it.ogt.ykcj.domain.exam.ExamStemInfo;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeCertificateRelation;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeInfo;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeSubjectGrade;
import com.hyt.it.ogt.ykcj.domain.param.EnterpriseScoreLineListParam;
import com.hyt.it.ogt.ykcj.domain.param.EnterpriseScoreLineSaveParam;
import com.hyt.it.ogt.ykcj.domain.param.ScoreLineItem;
import com.hyt.it.ogt.ykcj.domain.vo.*;
import com.hyt.it.ogt.ykcj.domain.zs.ZsExamineeInfo;
import com.hyt.it.ogt.ykcj.domain.zs.vo.ZsInfoVO;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamStemInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamSubjectInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exchange.CandidateInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeSubjectGradeMapper;
import com.hyt.it.ogt.ykcj.mapper.zs.ZsExamineeInfoMapper;
import com.hyt.it.ogt.ykcj.service.exam.IEnterpriseExamScoreLineSettingService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeCertificateRelationService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeGradeImportService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeInfoService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseGroupExamineeInfoService;
import com.hyt.it.ogt.ykcj.service.system.ISysDictDataService;
import com.hyt.it.ogt.ykcj.service.zs.IZsExamineeInfoService;
import com.hyt.it.ogt.ykcj.service.zs.IZsInfoService;
import com.hyt.loginfo.service.IBaseLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 企业招聘考生信息Service业务层处理
 *
 * @author liying
 * @date 2021-11-19
 */
@Slf4j
@Service
public class EnterpriseExamineeInfoServiceImpl extends BaseServiceImpl<EnterpriseExamineeInfoMapper, EnterpriseExamineeInfo> implements IEnterpriseExamineeInfoService {

    @Autowired
    private EnterpriseExamineeInfoMapper enterpriseExamineeInfoMapper;

    @Autowired
    private EnterpriseExamineeSubjectGradeMapper enterpriseExamineeSubjectGradeMapper;

    @Autowired
    private ExamInfoMapper examInfoMapper;

    @Autowired
    private ExamSubjectInfoMapper examSubjectInfoMapper;

    @Autowired
    private ExamStemInfoMapper examStemInfoMapper;

    @Autowired
    private IBaseLoginService iBaseLoginService;

    @Autowired
    private CandidateInfoMapper candidateInfoMapper;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IEnterpriseExamScoreLineSettingService enterpriseExamScoreLineSettingService;

    @Resource
    IEnterpriseExamineeCertificateRelationService enterpriseExamineeCertificateRelationService;
    @Autowired
    private IEnterpriseGroupExamineeInfoService enterpriseGroupExamineeInfoService;


    @Autowired
    private IZsInfoService zsInfoService;

    @Resource
    private ZsExamineeInfoMapper zsExamineeInfoMapper;

    @Resource
    private IZsExamineeInfoService iZsExamineeInfoService;


    /**
     * 查询企业招聘考生信息
     *
     * @param id 企业招聘考生信息ID
     * @return 企业招聘考生信息
     */
    @Override
    public EnterpriseExamineeInfo selectEnterpriseExamineeInfoById(String id) {
        return enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoById(id);
    }

    /**
     * 查询企业招聘考生信息列表
     *
     * @param enterpriseExamineeInfo 企业招聘考生信息
     * @return 企业招聘考生信息
     */
    @Override
    public List<EnterpriseExamineeInfo> selectEnterpriseExamineeInfoList(EnterpriseExamineeInfo enterpriseExamineeInfo) {
        return enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(enterpriseExamineeInfo);
    }

    @Override
    public List<EnterpriseExamineeInfo> selectEnterpriseExamineeInfoListRealName(EnterpriseExamineeInfo enterpriseExamineeInfo) {
        return enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoListRealName(enterpriseExamineeInfo);
    }

    /**
     * 分页查询企业招聘考生信息列表
     *
     * @param queryExamineeGradeVo
     * @return
     */
    @Override
    public PageInfo<List<EnterpriseExamineeInfoVo>> selectEnterpriseExamineeGradePage(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) {
        // 默认查询最后一场考试考生
        if (StringUtils.isEmpty(queryExamineeGradeVo.getExamId())) {
            ExamInfo examInfo = examInfoMapper.selectExamGroupInfoByExamType(queryExamineeGradeVo.getExamType(), queryExamineeGradeVo.getExamForm());
            queryExamineeGradeVo.setExamId(examInfo.getId());
        }
        queryExamineeGradeVo.setOfficeId(iBaseLoginService.getOfficeId());
        queryExamineeGradeVo.setDeptIds(iBaseLoginService.getDeptIds());
        //查询总成绩
        if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
            PageHelper.startPage(queryExamineeGradeVo.getPageNum(), queryExamineeGradeVo.getPageSize());
            List<EnterpriseExamineeInfoVo> enterpriseExamineeInfoVos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeGradePage(queryExamineeGradeVo);
            if (CollectionUtils.isEmpty(enterpriseExamineeInfoVos)) {
                return new PageInfo(Collections.emptyList());
            }
            Set<String> ids = enterpriseExamineeInfoVos.stream().map(e -> e.getId()).collect(Collectors.toSet());
            String[] examineeIds = ids.toArray(new String[ids.size()]);
            List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeSubjectByExamineeIds(examineeIds, queryExamineeGradeVo.getExamId());
            //总成绩 key exam_id + examinee_id
            Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamId() + c.getExamineeId()));
            for (EnterpriseExamineeInfoVo vo : enterpriseExamineeInfoVos) {
                if (MapUtils.isNotEmpty(subjectGradeMap) && null != subjectGradeMap.get(vo.getExamId() + vo.getId())) {
                    vo.setGradeList(subjectGradeMap.get(vo.getExamId() + vo.getId()));
                    vo.setScore(vo.getGradeList().stream().filter(e -> null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
                }
                // 装配考生信息
                this.assembleEnterpriseExamineeInfoVo(vo);
            }
            return new PageInfo(enterpriseExamineeInfoVos);
            //查询科目成绩
        } else {
            PageHelper.startPage(queryExamineeGradeVo.getPageNum(), queryExamineeGradeVo.getPageSize());
            List<EnterpriseExamineeInfoVo> enterpriseExamineeInfoVos = enterpriseExamineeInfoMapper.selectSubjectEnterpriseExamineeGradePage(queryExamineeGradeVo);
            if (CollectionUtils.isEmpty(enterpriseExamineeInfoVos)) {
                return new PageInfo(Collections.emptyList());
            }
            Set<String> ids = enterpriseExamineeInfoVos.stream().map(e -> e.getId()).collect(Collectors.toSet());
            String[] examineeIds = ids.toArray(new String[ids.size()]);

            List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeStemByExamineeIds(examineeIds, queryExamineeGradeVo.getExamId());
            //科目成绩 key exam_id + examinee_id + subject_id
            Map<String, List<EnterpriseExamineeSubjectGradeVo>> stemGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamId() + c.getExamineeId() + c.getSubjectId()));
            for (EnterpriseExamineeInfoVo vo : enterpriseExamineeInfoVos) {
                if (MapUtils.isNotEmpty(stemGradeMap) && null != stemGradeMap.get(vo.getExamId() + vo.getId() + vo.getSubjectId())) {
                    vo.setGradeList(stemGradeMap.get(vo.getExamId() + vo.getId() + vo.getSubjectId()));
//                    vo.setScore(vo.getGradeList().stream().map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));

                }
                // 装配考生信息
                this.assembleEnterpriseExamineeInfoVo(vo);
            }
            return new PageInfo(enterpriseExamineeInfoVos);
        }

    }

    /**
     * 装配考生信息
     *
     * @param vo
     */
    private void assembleEnterpriseExamineeInfoVo(EnterpriseExamineeInfoVo vo) {
        List<String> enterpriseExamineeCertificateRelations = enterpriseExamineeCertificateRelationService.listNameByExamineeInfoId(vo.getId());
        vo.setZsInfoNames(enterpriseExamineeCertificateRelations);
    }

    /**
     * 新增企业招聘考生信息
     *
     * @param enterpriseExamineeInfo 企业招聘考生信息
     * @return 结果
     */
    @Override
    public int insertEnterpriseExamineeInfo(EnterpriseExamineeInfo enterpriseExamineeInfo) {
        enterpriseExamineeInfo.setId(IdUtils.generateId());
        enterpriseExamineeInfo.setCreateTime(DateUtils.getNowDate());
        enterpriseExamineeInfo.setDeptId(iBaseLoginService.getDeptId());
        enterpriseExamineeInfo.setOfficeId(iBaseLoginService.getOfficeId());
        enterpriseExamineeInfo.setQualifiedStatus(CommonEnums.QUALIFIED_STATUS_D.getCode());
        enterpriseExamineeInfo.setArchivedStatus(CommonEnums.ARCHIVED_STATUS_N.getCode());
        enterpriseExamineeInfo.setOrigin(Integer.valueOf(CommonEnums.ORIGIN_0.getCode()));
        return enterpriseExamineeInfoMapper.insertEnterpriseExamineeInfo(enterpriseExamineeInfo);
    }

    /**
     * 修改企业招聘考生信息
     *
     * @param enterpriseExamineeInfo 企业招聘考生信息
     * @return 结果
     */
    @Override
    public int updateEnterpriseExamineeInfo(EnterpriseExamineeInfo enterpriseExamineeInfo) {
        enterpriseExamineeInfo.setUpdateTime(DateUtils.getNowDate());
        return enterpriseExamineeInfoMapper.updateEnterpriseExamineeInfo(enterpriseExamineeInfo);
    }

    /**
     * 批量删除企业招聘考生信息
     *
     * @param queryExamineeGradeVo
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEnterpriseExamineeGrade(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) throws Exception {

        if (StringUtils.isEmpty(queryExamineeGradeVo.getExamId())) {
            throw new CustomException("考试ID不能为空！");
        }
        checkExamineeOrigin(queryExamineeGradeVo.getExamId());
        if (!CommonEnums.ARCHIVED_STATUS_Y.getCode().equals(queryExamineeGradeVo.getArchivedStatus())) {
            Integer count = enterpriseExamineeSubjectGradeMapper.countArchivedExamineeSubjectGrade(new String[]{queryExamineeGradeVo.getExamId()}, queryExamineeGradeVo.getExamineeIds());
            if (null != count && count.intValue() > 0 && StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
                throw new CustomException("考试下存在已归档考生成绩数据，不允许删除!");
            }
        }

        if ("1".equals(queryExamineeGradeVo.getTickFlag())) {
            //删除总成绩
            if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
                enterpriseExamineeInfoMapper.deleteEnterpriseExamineeInfoByExamId(queryExamineeGradeVo.getExamId());
                enterpriseExamineeSubjectGradeMapper.deleteEnterpriseExamineeSubjectGradeByExamId(queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());
            } else {
                enterpriseExamineeSubjectGradeMapper.deleteEnterpriseExamineeSubjectGradeByExamId(queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());
            }
            return 1;
        }

        if (null == queryExamineeGradeVo.getExamineeIds() || queryExamineeGradeVo.getExamineeIds().length < 1) {
            throw new CustomException("考生ID不能为空！");
        }
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryExamineeGradeVo.getExamineeIds()));
        if (CollectionUtils.isEmpty(enterpriseExamineeInfos)) {
            throw new CustomException("查询不到考生信息！");
        }
        List<Integer> origins = enterpriseExamineeInfos.stream().map(EnterpriseExamineeInfo::getOrigin).collect(Collectors.toList());
        if (origins.contains(Integer.valueOf(CommonEnums.ORIGIN_1.getCode()))) {
            throw new CustomException("考生有同步数据，不能删除！");
        }

        //删除总成绩
        if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
            enterpriseExamineeInfoMapper.deleteEnterpriseExamineeInfoByIds(queryExamineeGradeVo.getExamineeIds());
            enterpriseExamineeSubjectGradeMapper.deleteEnterpriseExamineeSubjectGradeByExamineeIds(queryExamineeGradeVo.getExamineeIds(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());
        } else {//删除科目
            enterpriseExamineeSubjectGradeMapper.deleteEnterpriseExamineeSubjectGradeByExamineeIds(queryExamineeGradeVo.getExamineeIds(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());
        }
        return 1;

    }

    /**
     * 删除企业招聘考生信息信息
     *
     * @param id 企业招聘考生信息ID
     * @return 结果
     */
    @Override
    public int deleteEnterpriseExamineeInfoById(String id) {
        return enterpriseExamineeInfoMapper.deleteEnterpriseExamineeInfoById(id);
    }

    /**
     * 获取企业招聘考生成绩信息详细
     *
     * @param id 企业招聘考生信息ID
     * @return 企业招聘生成绩信息详细
     */
    @Override
    public AddEnterpriseExamineeInfoVo selectEnterpriseExamineeGradeById(String id) {
        AddEnterpriseExamineeInfoVo enterpriseExamineeInfoVo = new AddEnterpriseExamineeInfoVo();
        EnterpriseExamineeInfo enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoById(id);
        BeanUtils.copyBeanProp(enterpriseExamineeInfoVo, enterpriseExamineeInfo);
        EnterpriseExamineeSubjectGrade enterpriseExamineeSubjectGrade = new EnterpriseExamineeSubjectGrade();
        enterpriseExamineeSubjectGrade.setExamineeId(enterpriseExamineeInfo.getId());
        List<EnterpriseExamineeSubjectGrade> gradeList = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeSubjectGradeList(enterpriseExamineeSubjectGrade);
        List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectInfoByExamId(enterpriseExamineeInfo.getExamId());
        Map<String, String> subjectNameMap = null;
        if (CollectionUtils.isNotEmpty(examSubjectVos)) {
            subjectNameMap = examSubjectVos.stream().collect(Collectors.toMap(ExamSubjectVo::getSubjectId, ExamSubjectVo::getSubjectName, (k1, k2) -> k2));
        }

        List<AddEnterpriseExamineeSubjectGradeVo> subjectGradeVoList = new ArrayList<>();
        List<AddEnterpriseExamineeStemGradeVo> stemGradeVoList = new ArrayList<>();
        for (EnterpriseExamineeSubjectGrade grade : gradeList) {
            //科目
            if (StringUtils.isEmpty(grade.getStemId())) {
                AddEnterpriseExamineeSubjectGradeVo gradeVo = new AddEnterpriseExamineeSubjectGradeVo();
                BeanUtils.copyBeanProp(gradeVo, grade);
                gradeVo.setSubjectName(MapUtils.isNotEmpty(subjectNameMap) ? subjectNameMap.get(grade.getSubjectId()) : null);
                subjectGradeVoList.add(gradeVo);
            } else {//题干
                ExamStemInfo examStemInfo = new ExamStemInfo();
                examStemInfo.setSubjectId(grade.getSubjectId());
                List<ExamStemInfo> examStemInfos = examStemInfoMapper.selectExamStemInfoList(examStemInfo);
                AddEnterpriseExamineeStemGradeVo gradeVo = new AddEnterpriseExamineeStemGradeVo();
                BeanUtils.copyBeanProp(gradeVo, grade);
                if (CollectionUtils.isNotEmpty(examStemInfos)) {
                    Map<String, String> stemNameMap = examStemInfos.stream().collect(Collectors.toMap(ExamStemInfo::getId, ExamStemInfo::getName, (k1, k2) -> k2));
                    gradeVo.setStemName(MapUtils.isNotEmpty(stemNameMap) ? stemNameMap.get(grade.getStemId()) : null);
                }
                stemGradeVoList.add(gradeVo);
            }
        }
        Map<String, List<AddEnterpriseExamineeStemGradeVo>> stemMap = stemGradeVoList.stream().collect(Collectors.groupingBy(c -> c.getSubjectId()));
        for (AddEnterpriseExamineeSubjectGradeVo subjectGradeVo : subjectGradeVoList) {
            subjectGradeVo.setGradeList(stemMap.get(subjectGradeVo.getSubjectId()));
        }
        enterpriseExamineeInfoVo.setGradeList(subjectGradeVoList);
        return enterpriseExamineeInfoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveEnterpriseExamineeGrade(AddEnterpriseExamineeInfoVo enterpriseExamineeInfoVo) throws Exception {
        this.checkExamineeGrade(enterpriseExamineeInfoVo); // 提交数据检查
        checkExamineeOrigin(enterpriseExamineeInfoVo.getExamId());
        List<EnterpriseExamineeInfo> examineeInfos = enterpriseExamineeInfoMapper.selectAdmissionNos(enterpriseExamineeInfoVo.getAdmissionNo(), enterpriseExamineeInfoVo.getExamId(), "");
        if (CollectionUtils.isNotEmpty(examineeInfos)) {
            Set<Integer> originSet = examineeInfos.stream().map(e -> e.getOrigin()).collect(Collectors.toSet());
            if (originSet.contains(Integer.valueOf(CommonEnums.ORIGIN_1.getCode()))) {
                throw new CustomException("考生：" + examineeInfos.get(0).getName() + "，准考证号：" + examineeInfos.get(0).getAdmissionNo() + "，数据是上游同步数据，不允许修改！");
            }
            if (!examineeInfos.get(0).getId().equals(enterpriseExamineeInfoVo.getId())) {
                throw new CustomException("同一场考试存在相同的准考证号：" + enterpriseExamineeInfoVo.getAdmissionNo() + "，请仔细检查！");
            }
        }
        examineeInfos = enterpriseExamineeInfoMapper.selectAdmissionNos("", enterpriseExamineeInfoVo.getExamId(), enterpriseExamineeInfoVo.getIdcard());
        if (CollectionUtils.isNotEmpty(examineeInfos)) {
            if (!examineeInfos.get(0).getId().equals(enterpriseExamineeInfoVo.getId())) {
                throw new CustomException("同一场考试存在相同的证件号:" + enterpriseExamineeInfoVo.getIdcard() + "，请仔细检查！");
            }
        }
        Set<String> gradeSet = new TreeSet<>();
        EnterpriseExamineeInfo enterpriseExamineeInfo = new EnterpriseExamineeInfo();
        BeanUtils.copyBeanProp(enterpriseExamineeInfo, enterpriseExamineeInfoVo);

        List<EnterpriseExamineeSubjectGradeVo> examineeSubjectGradeList = new ArrayList<>();
        //科目
        for (AddEnterpriseExamineeSubjectGradeVo subjectGradeVo : enterpriseExamineeInfoVo.getGradeList()) {
            EnterpriseExamineeSubjectGradeVo gradeVo = new EnterpriseExamineeSubjectGradeVo();
            BeanUtils.copyBeanProp(gradeVo, subjectGradeVo);
            gradeVo.setExamId(enterpriseExamineeInfoVo.getExamId());
            gradeVo.setSubjectFlag(CommonEnums.SUBJECT_FLAG_K.getCode());
            examineeSubjectGradeList.add(gradeVo);
            //题目
            if (CollectionUtils.isNotEmpty(subjectGradeVo.getGradeList())) {
                BigDecimal gradeScore = new BigDecimal("0");
                for (AddEnterpriseExamineeStemGradeVo stemGradeVo : subjectGradeVo.getGradeList()) {
                    gradeVo = new EnterpriseExamineeSubjectGradeVo();
                    BeanUtils.copyBeanProp(gradeVo, stemGradeVo);
                    gradeVo.setExamId(enterpriseExamineeInfoVo.getExamId());
                    gradeVo.setSubjectId(subjectGradeVo.getSubjectId());
                    gradeVo.setSubjectFlag(CommonEnums.SUBJECT_FLAG_T.getCode());
                    examineeSubjectGradeList.add(gradeVo);
                    gradeScore = gradeScore.add(gradeVo.getScore());
                }
                if (0 != subjectGradeVo.getScore().compareTo(gradeScore)) {
                    throw new CustomException("科目总分不等于题型分数之和");
                }
            }

        }
        //查询考试设置的科目分数线
        List<EnterpriseScoreLineSaveParam> scoreLineSettings = enterpriseExamScoreLineSettingService.getScoreLineList(enterpriseExamineeInfoVo.getExamId(), null, null);
        // 科目分数线
        Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getDimension()));
        List<EnterpriseScoreLineSaveParam> subjectScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_1.getCode());
        Map<String, List<ScoreLineItem>> subjectSngleScoreLineItemMap = getSngleScoreLineItemMap(subjectScoreLineSettings);
        List<ScoreLineItem> subjectRegionScoreLineItemList = getRegionScoreLineItems(subjectScoreLineSettings);

        //考试分数线
        List<EnterpriseScoreLineSaveParam> examScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_0.getCode());
        Map<String, List<ScoreLineItem>> examCompositeScoreLineItemMap = getCompositeScoreLineItemMap(examScoreLineSettings);
        Map<String, List<ScoreLineItem>> examSngleScoreLineItemMap = getSngleScoreLineItemMap(examScoreLineSettings);
        List<ScoreLineItem> examRegionScoreLineItemList = getRegionScoreLineItems(examScoreLineSettings);

        List<EnterpriseExamineeSubjectGrade> allGradeList = new ArrayList<>();
        if (StringUtils.isNotEmpty(enterpriseExamineeInfo.getId())) { // 更新
            enterpriseExamineeInfo.updateInfo(iBaseLoginService.getSysUser().getLoginname());
            List<EnterpriseExamineeSubjectGrade> insertGradeList = new ArrayList<>();
            List<EnterpriseExamineeSubjectGrade> updateGradeList = new ArrayList<>();
            List<String> deleteGradeList = new ArrayList<>();
            for (EnterpriseExamineeSubjectGradeVo gradeVo : examineeSubjectGradeList) {
                if (gradeSet.contains(gradeVo.getSubjectId() + gradeVo.getStemId())) {
                    throw new CustomException(BizErrorCode.COM_E0005);
                } else {
                    gradeSet.add(gradeVo.getSubjectId() + gradeVo.getStemId());
                }
                EnterpriseExamineeSubjectGrade grade = new EnterpriseExamineeSubjectGrade();
                BeanUtils.copyBeanProp(grade, gradeVo);
                if (StringUtils.isEmpty(grade.getId()) && !CommonEnums.DATA_DEL_FLAG_D.getCode().equals(grade.getDelFlag())) {
                    grade.setId(IdUtils.generateId());
                    grade.setExamId(enterpriseExamineeInfo.getExamId());
                    grade.setExamineeId(enterpriseExamineeInfo.getId());
                    if (StringUtils.isEmpty(grade.getStemId())) {
                        grade.setStemId("");
                        grade.setQualifiedStatus(getGradeQualifiedStatus(grade, subjectSngleScoreLineItemMap));
                        grade.setRegionName(getSubjectRegionName(subjectRegionScoreLineItemList, grade));
                    } else {
                        grade.setQualifiedStatus("");
                        grade.setRegionName("");
                    }
                    grade.createInfo(iBaseLoginService.getSysUser().getLoginname());
                    grade.updateInfo(iBaseLoginService.getSysUser().getLoginname());
                    grade.setDeptId(iBaseLoginService.getDeptId());
                    grade.setOfficeId(iBaseLoginService.getOfficeId());
                    grade.setArchivedStatus(CommonEnums.ARCHIVED_STATUS_N.getCode());
                    insertGradeList.add(grade);
                } else if (StringUtils.isNotEmpty(grade.getId()) && !CommonEnums.DATA_DEL_FLAG_D.getCode().equals(grade.getDelFlag())) {
                    grade.updateInfo(iBaseLoginService.getSysUser().getLoginname());
                    if (StringUtils.isEmpty(grade.getStemId())) {
                        grade.setStemId("");
                        grade.setQualifiedStatus(getGradeQualifiedStatus(grade, subjectSngleScoreLineItemMap));
                        grade.setRegionName(getSubjectRegionName(subjectRegionScoreLineItemList, grade));
                    } else {
                        grade.setQualifiedStatus("");
                        grade.setRegionName("");
                    }
                    updateGradeList.add(grade);
                } else if (StringUtils.isNotEmpty(grade.getId()) && CommonEnums.DATA_DEL_FLAG_D.getCode().equals(grade.getDelFlag())) {
                    deleteGradeList.add(grade.getId());
                }
            }
            if (CollectionUtils.isNotEmpty(insertGradeList)) {
                allGradeList.addAll(insertGradeList);
                enterpriseExamineeSubjectGradeMapper.insertBatchEnterpriseExamineeSubjectGrade(insertGradeList);
            }
            if (CollectionUtils.isNotEmpty(deleteGradeList)) {
                enterpriseExamineeSubjectGradeMapper.deleteEnterpriseExamineeSubjectGradeByIds(deleteGradeList.toArray(new String[deleteGradeList.size()]));
            }
            allGradeList.addAll(updateGradeList);
            if (CollectionUtils.isNotEmpty(updateGradeList)) {
                enterpriseExamineeSubjectGradeMapper.updateBatchEnterpriseExamineeSubjectGrade(updateGradeList);
            }

            enterpriseExamineeInfo.setQualifiedStatus(getExamQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, allGradeList));
            enterpriseExamineeInfo.setRegionName(getExamRegionName(examRegionScoreLineItemList, allGradeList));
            int ret = enterpriseExamineeInfoMapper.updateEnterpriseExamineeInfo(enterpriseExamineeInfo);
            //考试组(查询考试组设置的分数线，更新考试组的合格状态)
            ExamInfo examInfo = examInfoMapper.selectExamInfoById(enterpriseExamineeInfoVo.getExamId());
            ExamInfo groupExamInfo = examInfoMapper.selectExamInfoById(examInfo.getRelationId());
            //合并考试
            if (null != groupExamInfo && CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(groupExamInfo.getMergeType()))) {
                Map<String, String> tempMap = enterpriseGroupExamineeInfoService.getGroupQualifiedStatusAndRegionName(groupExamInfo.getId(), enterpriseExamineeInfo.getIdcard(), enterpriseExamineeInfo.getName());
                enterpriseExamineeInfo.setGroupQualifiedStatus(tempMap.get("qualifiedStatus"));
                enterpriseExamineeInfo.setGroupRegionName(tempMap.get("regionname"));
                List<String> ids = Arrays.asList(tempMap.get("examineeIds").split(","));
                Set<String> examineeIds = new HashSet<>(ids.size());
                for (String id : ids) {
                    if (id.equals(enterpriseExamineeInfo.getId())) {
                        continue;
                    }
                    examineeIds.add(id);
                }

                enterpriseExamineeInfoMapper.updateGroupQualifiedStatusAndRegionNameByIds(tempMap.get("qualifiedStatus"), tempMap.get("regionname"), examineeIds.toArray(new String[examineeIds.size()]));
            }

            return ret;
        } else { // 新增
            EnterpriseExamineeInfo enterpriseExamineeInfoParams = new EnterpriseExamineeInfo();
            enterpriseExamineeInfoParams.setExamId(enterpriseExamineeInfo.getExamId());
            enterpriseExamineeInfoParams.setIdcard(enterpriseExamineeInfo.getIdcard());
            List<EnterpriseExamineeInfo> existingEnterpriseExamineeInfolist = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(enterpriseExamineeInfoParams);
            if (!CollectionUtils.isEmpty(existingEnterpriseExamineeInfolist)) { // 考生信息已存在则用已有信息
                BeanUtils.copyBeanProp(enterpriseExamineeInfo, existingEnterpriseExamineeInfolist.get(0));
                enterpriseExamineeInfo.updateInfo(iBaseLoginService.getSysUser().getLoginname());
            } else {
                enterpriseExamineeInfo.setId(IdUtils.generateId());
                enterpriseExamineeInfo.createInfo(iBaseLoginService.getSysUser().getLoginname());
                enterpriseExamineeInfo.updateInfo(iBaseLoginService.getSysUser().getLoginname());
                enterpriseExamineeInfo.setDeptId(iBaseLoginService.getDeptId());
                enterpriseExamineeInfo.setOfficeId(iBaseLoginService.getOfficeId());
                enterpriseExamineeInfo.setArchivedStatus(CommonEnums.ARCHIVED_STATUS_N.getCode());
                enterpriseExamineeInfo.setOrigin(Integer.valueOf(CommonEnums.ORIGIN_0.getCode()));
                enterpriseExamineeInfo.setQualifiedStatus("");
            }

            List<EnterpriseExamineeSubjectGrade> gradeList = new ArrayList<>();
            for (EnterpriseExamineeSubjectGradeVo gradeVo : examineeSubjectGradeList) {
                if (gradeSet.contains(gradeVo.getSubjectId() + gradeVo.getStemId())) {
                    throw new CustomException(BizErrorCode.COM_E0005);
                } else {
                    gradeSet.add(gradeVo.getSubjectId() + gradeVo.getStemId());
                }
                EnterpriseExamineeSubjectGrade grade = new EnterpriseExamineeSubjectGrade();
                BeanUtils.copyBeanProp(grade, gradeVo);
                grade.setId(IdUtils.generateId());
                grade.setExamId(enterpriseExamineeInfo.getExamId());
                grade.setExamineeId(enterpriseExamineeInfo.getId());
                if (StringUtils.isEmpty(grade.getStemId())) {
                    grade.setStemId("");
                    grade.setQualifiedStatus(getGradeQualifiedStatus(grade, subjectSngleScoreLineItemMap));
                    grade.setRegionName(getSubjectRegionName(subjectRegionScoreLineItemList, grade));
                } else {
                    grade.setQualifiedStatus(CommonEnums.QUALIFIED_STATUS_D.getCode());
                    grade.setRegionName(CommonEnums.QUALIFIED_STATUS_D.getCode());
                }
                grade.setDeptId(iBaseLoginService.getDeptId());
                grade.setOfficeId(iBaseLoginService.getOfficeId());
                grade.setArchivedStatus(CommonEnums.ARCHIVED_STATUS_N.getCode());
                grade.createInfo(iBaseLoginService.getSysUser().getLoginname());
                grade.updateInfo(iBaseLoginService.getSysUser().getLoginname());
                gradeList.add(grade);
            }
            allGradeList.addAll(gradeList);
            enterpriseExamineeSubjectGradeMapper.insertBatchEnterpriseExamineeSubjectGrade(gradeList);
            try {

                enterpriseExamineeInfo.setQualifiedStatus(getExamQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, allGradeList));
                enterpriseExamineeInfo.setRegionName(getExamRegionName(examRegionScoreLineItemList, allGradeList));
                int ret = enterpriseExamineeInfoMapper.insertEnterpriseExamineeInfo(enterpriseExamineeInfo);
                //考试组(查询考试组设置的分数线，更新考试组的合格状态)
                ExamInfo examInfo = examInfoMapper.selectExamInfoById(enterpriseExamineeInfoVo.getExamId());
                ExamInfo groupExamInfo = examInfoMapper.selectExamInfoById(examInfo.getRelationId());
                //合并考试
                if (null != groupExamInfo && CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(groupExamInfo.getMergeType()))) {
                    Map<String, String> tempMap = enterpriseGroupExamineeInfoService.getGroupQualifiedStatusAndRegionName(groupExamInfo.getId(), enterpriseExamineeInfo.getIdcard(), enterpriseExamineeInfo.getName());
                    enterpriseExamineeInfo.setGroupQualifiedStatus(tempMap.get("qualifiedStatus"));
                    enterpriseExamineeInfo.setGroupRegionName(tempMap.get("regionname"));
                    List<String> ids = Arrays.asList(tempMap.get("examineeIds").split(","));
                    enterpriseExamineeInfoMapper.updateGroupQualifiedStatusAndRegionNameByIds(tempMap.get("qualifiedStatus"), tempMap.get("regionname"), ids.toArray(new String[ids.size()]));
                }
                return ret;
            } catch (DuplicateKeyException e) {
                log.error("保存考生数据异常:{}", e);
                throw new CustomException("删除数据异常！");
            }
        }
    }


    /**
     * 考生总成绩合格设置
     *
     * @param regionScoreLineItemList 设置分数线 区间
     * @param grade                   考试所以的科目
     */
    @Override
    public String getSubjectRegionName(List<ScoreLineItem> regionScoreLineItemList, EnterpriseExamineeSubjectGrade grade) {
        if (null == grade) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        if (CollectionUtils.isEmpty(regionScoreLineItemList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        Map<String, List<ScoreLineItem>> regionScoreLineItemMap = regionScoreLineItemList.stream().collect(Collectors.groupingBy(c -> c.getSubjectId()));

        //找出包含区间科目
        List<ScoreLineItem> items = regionScoreLineItemMap.get(grade.getSubjectId());
        if (CollectionUtils.isEmpty(items)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        for (ScoreLineItem item : items) {
            if (null == grade.getScore()) {
                return CommonEnums.QUALIFIED_STATUS_N.getCode();
            }
            if (grade.getScore().compareTo(new BigDecimal(item.getRegionStartScore())) > -1
                    && grade.getScore().compareTo(new BigDecimal(item.getRegionEndScore())) < 0) {
                return item.getRegionName();
            }
        }

        return CommonEnums.QUALIFIED_STATUS_D.getCode();

    }


    /**
     * 考生总成绩合格设置
     *
     * @param regionScoreLineItemList 设置分数线 区间
     * @param allGradeList            考试所以的科目
     */
    @Override
    public String getExamRegionName(List<ScoreLineItem> regionScoreLineItemList, List<EnterpriseExamineeSubjectGrade> allGradeList) {
        if (CollectionUtils.isEmpty(regionScoreLineItemList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        if (CollectionUtils.isEmpty(allGradeList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        //所以科目分数
        Map<String, BigDecimal> scoreMap = allGradeList.stream().filter(e -> StringUtils.isEmpty(e.getStemId())).collect(Collectors.toMap(EnterpriseExamineeSubjectGrade::getSubjectId, EnterpriseExamineeSubjectGrade::getScore, (key1, key2) -> key2));

        //区间分数线 -- 找出复合未合格的直接返回
        Set<String> subjectIds = regionScoreLineItemList.stream().map(s -> s.getSubjectId()).collect(Collectors.toSet());
        BigDecimal tempScore = BigDecimal.ZERO;
        for (String sid : subjectIds) {
            //求和考生成绩
            if (null == scoreMap.get(sid)) {
                continue;
            }
            tempScore = tempScore.add(scoreMap.get(sid));

        }
        //按科目分组，只需要取任意一组科目的区间。设置分数区间分数线时都存一样的，所以随机取一组即可
        Map<String, List<ScoreLineItem>> regionScoreLineItemMap = regionScoreLineItemList.stream().collect(Collectors.groupingBy(c -> c.getSubjectId()));
        String firstKey = regionScoreLineItemMap.keySet().stream().findFirst().get();
        List<ScoreLineItem> items = regionScoreLineItemMap.get(firstKey);
        if (CollectionUtils.isEmpty(items)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        for (ScoreLineItem item : items) {
            if (tempScore.compareTo(new BigDecimal(item.getRegionStartScore())) > -1
                    && tempScore.compareTo(new BigDecimal(item.getRegionEndScore())) < 0) {
                return item.getRegionName();
            }
        }
//        for (String key : regionScoreLineItemMap.keySet()) {
//            //找出包含区间科目
//            List<ScoreLineItem> items = regionScoreLineItemMap.get(key);
//            if (CollectionUtils.isEmpty(items)) {
//                break;
//            }
//            for (ScoreLineItem item : items) {
//                if (tempScore.compareTo(new BigDecimal(item.getRegionStartScore())) > -1
//                        && tempScore.compareTo(new BigDecimal(item.getRegionEndScore())) < 0) {
//                    return item.getRegionName();
//                }
//            }
//            break;
//        }
        return CommonEnums.QUALIFIED_STATUS_D.getCode();

    }


    /**
     * 考生总成绩合格设置
     *
     * @param sngleScoreLineItemMap     设置分数线 单科
     * @param compositeScoreLineItemMap 设置分数线 复合
     * @param allGradeList              考试所以的科目
     */
    @Override
    public String getExamQualifiedStatus(Map<String, List<ScoreLineItem>> sngleScoreLineItemMap
            , Map<String, List<ScoreLineItem>> compositeScoreLineItemMap, List<EnterpriseExamineeSubjectGrade> allGradeList) {
        if (MapUtils.isEmpty(sngleScoreLineItemMap) && MapUtils.isEmpty(compositeScoreLineItemMap)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        if (CollectionUtils.isEmpty(allGradeList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }

        //单科分数线 找出单科未合格的直接返回
        if (MapUtils.isNotEmpty(sngleScoreLineItemMap)) {
            //考生是否考了已全部科目，没考则直接不合格
            if (sngleScoreLineItemMap.keySet().size() > allGradeList.size()) {
                return CommonEnums.QUALIFIED_STATUS_N.getCode();
            }
            Map<String, BigDecimal> scoreMap = allGradeList.stream().filter(e -> StringUtils.isEmpty(e.getStemId())).collect(Collectors.toMap(EnterpriseExamineeSubjectGrade::getSubjectId, EnterpriseExamineeSubjectGrade::getScore, (key1, key2) -> key2));

            for (String key : sngleScoreLineItemMap.keySet()) {
                if (null == scoreMap.get(key)) {
                    continue;
                }
                List<ScoreLineItem> items = sngleScoreLineItemMap.get(key);
                for (ScoreLineItem item : items) {
                    if (CommonEnums.COMPARISON_TYPE_1.getCode().equals(item.getComparisonType()) && StringUtils.isNotEmpty(item.getScore())
                            && scoreMap.get(key).compareTo(new BigDecimal(item.getScore())) > -1) {
                        continue;
                    } else if (CommonEnums.COMPARISON_TYPE_0.getCode().equals(item.getComparisonType()) && StringUtils.isNotEmpty(item.getScore())
                            && scoreMap.get(key).compareTo(new BigDecimal(item.getScore())) > 0) {
                        continue;
                    } else {
                        return CommonEnums.QUALIFIED_STATUS_N.getCode();
                    }
                }
            }
        }
        //复合分数线 -- 找出复合未合格的直接返回
        if (MapUtils.isNotEmpty(compositeScoreLineItemMap)) {
            //所以科目分数
            Map<String, BigDecimal> scoreMap = allGradeList.stream()
                    .filter(e -> StringUtils.isEmpty(e.getStemId()))
                    .filter(e -> StrUtil.isNotBlank(e.getSubjectId()))
                    .filter(e -> ObjectUtil.isNotEmpty(e.getScore()))
                    .collect(Collectors.toMap(EnterpriseExamineeSubjectGrade::getSubjectId, EnterpriseExamineeSubjectGrade::getScore));
            for (String key : compositeScoreLineItemMap.keySet()) {
                //找出包含复合科目
                List<ScoreLineItem> items = compositeScoreLineItemMap.get(key);
                Set<String> subjectIds = items.stream().map(s -> s.getSubjectId()).collect(Collectors.toSet());
                BigDecimal tempScore = new BigDecimal("0");
                //求和考生复合成绩
                for (String sid : subjectIds) {
                    if (null == scoreMap.get(sid)) {
                        continue;
                    }
                    tempScore = tempScore.add(scoreMap.get(sid));
                }
                if (CommonEnums.COMPARISON_TYPE_1.getCode().equals(items.get(0).getComparisonType()) && StringUtils.isNotEmpty(items.get(0).getScore())
                        && tempScore.compareTo(new BigDecimal(items.get(0).getScore())) > -1) {
                    continue;
                } else if (CommonEnums.COMPARISON_TYPE_0.getCode().equals(items.get(0).getComparisonType()) && StringUtils.isNotEmpty(items.get(0).getScore())
                        && tempScore.compareTo(new BigDecimal(items.get(0).getScore())) > 0) {
                    continue;
                } else {
                    return CommonEnums.QUALIFIED_STATUS_N.getCode();
                }
            }
        }
        return CommonEnums.QUALIFIED_STATUS_Y.getCode();

    }


    /**
     * 科目分数线合格设置
     *
     * @param grade
     */
    @Override
    public String getGradeQualifiedStatus(EnterpriseExamineeSubjectGrade grade, Map<String, List<ScoreLineItem>> sngleScoreLineItemMap) {
        //题型设置为空字符
        if (StringUtils.isNotEmpty(grade.getStemId())) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }

        if (MapUtils.isEmpty(sngleScoreLineItemMap)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        List<ScoreLineItem> scoreLineItems = sngleScoreLineItemMap.get(grade.getSubjectId());
        if (CollectionUtils.isEmpty(scoreLineItems) || null == grade.getScore()) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        for (ScoreLineItem item : scoreLineItems) {
            if (null != item.getScore() && CommonEnums.COMPARISON_TYPE_1.getCode().equals(item.getComparisonType()) &&
                    grade.getScore().compareTo(new BigDecimal(item.getScore())) > -1) {
                return CommonEnums.QUALIFIED_STATUS_Y.getCode();
            } else if (null != item.getScore() && CommonEnums.COMPARISON_TYPE_0.getCode().equals(item.getComparisonType()) &&
                    grade.getScore().compareTo(new BigDecimal(item.getScore())) > 0) {
                return CommonEnums.QUALIFIED_STATUS_Y.getCode();
            } else {
                return CommonEnums.QUALIFIED_STATUS_N.getCode();
            }
        }
        return CommonEnums.QUALIFIED_STATUS_D.getCode();

    }

    /**
     * 企业招聘考生成绩信息提交检查
     *
     * @param enterpriseExamineeInfoVo 企业招聘考生成绩信息
     * @throws Exception
     */
    private void checkExamineeGrade(AddEnterpriseExamineeInfoVo enterpriseExamineeInfoVo) throws Exception {
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getExamId())) {
            throw new CustomException("考试ID不能为空");
        }
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getName())) {
            throw new CustomException("考生姓名不能为空");
        }
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getAdmissionNo())) {
            throw new CustomException("准考证号不能为空");
        }
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getIdcard())) {
            throw new CustomException("身份证号不能为空");
        }
        if (enterpriseExamineeInfoVo.getIdcard().length() > 50) {
            throw new CustomException("证件号长度超限");
        }
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getSex())) {
            throw new CustomException("性别未选择");
        }
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getMobile())) {
            throw new CustomException("联系方式不能为空");
        }
        if (StringUtils.isEmpty(enterpriseExamineeInfoVo.getEducation())) {
            throw new CustomException("学历不能为空");
        }
        if (CollectionUtils.isEmpty(enterpriseExamineeInfoVo.getGradeList())) {
            throw new CustomException("考生科目不能为空");
        }
        Map<String, ExamSubjectVo> examSubjectMap = existsExamSubject(enterpriseExamineeInfoVo.getExamId());

        Map<String, ExamStemInfo> examStemMap = existsExamStem(enterpriseExamineeInfoVo.getExamId(), examSubjectMap);

        for (AddEnterpriseExamineeSubjectGradeVo gradeVo : enterpriseExamineeInfoVo.getGradeList()) {
            if (StringUtils.isNotEmpty(gradeVo.getDelFlag()) && "N".equals(gradeVo.getDelFlag())) {
                if (StringUtils.isEmpty(gradeVo.getSubjectId())) {
                    throw new CustomException("科目未选择");
                }
                if (StringUtils.isEmpty(gradeVo.getScore().toString())) {
                    throw new CustomException("成绩不能为空");
                }
                if (null != examSubjectMap.get(gradeVo.getSubjectId())
                        && gradeVo.getScore().compareTo(examSubjectMap.get(gradeVo.getSubjectId()).getPaperFullMarks()) == 1) {
                    throw new CustomException("科目得分不能大于科目满分");
                }
            }
            if (CollectionUtils.isNotEmpty(gradeVo.getGradeList())) {
                for (AddEnterpriseExamineeStemGradeVo stemGradeVo : gradeVo.getGradeList()) {
                    if (StringUtils.isNotEmpty(stemGradeVo.getDelFlag()) && "N".equals(stemGradeVo.getDelFlag())) {
                        if (StringUtils.isEmpty(stemGradeVo.getStemId())) {
                            throw new CustomException("题干未选择");
                        }
                        if (StringUtils.isEmpty(stemGradeVo.getScore().toString())) {
                            throw new CustomException("成绩不能为空");
                        }
                        if (null != examStemMap.get(stemGradeVo.getStemId())
                                && stemGradeVo.getScore().compareTo(examStemMap.get(stemGradeVo.getStemId()).getTotalPoints()) == 1) {
                            throw new CustomException("题目得分不能大于题目满分");
                        }
                    }
                }
            }

        }

    }

    @Override
    public Map<String, ExamStemInfo> existsExamStem(String examId, Map<String, ExamSubjectVo> examSubjectMap) {
        if (MapUtils.isEmpty(examSubjectMap)) {
            return Collections.EMPTY_MAP;
        }
        List<String> subjectIds = examSubjectMap.keySet().stream().collect(Collectors.toList());
        List<ExamStemInfo> examStemInfos = examStemInfoMapper.selectOldStem(examId, subjectIds);
        Map<String, ExamStemInfo> examStemMap = examStemInfos.stream().filter(Objects::nonNull).collect(Collectors.toMap(ExamStemInfo::getId, o -> o, (key1, key2) -> key2));

        return examStemMap;
    }

    @Override
    public Map<String, ExamSubjectVo> existsExamSubject(String examId) {
        List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectInfoByExamId(examId);
        if (CollectionUtils.isEmpty(examSubjectVos)) {
            return Collections.EMPTY_MAP;
        }
        Map<String, ExamSubjectVo> examSubjectMap = examSubjectVos.stream().collect(Collectors.toMap(ExamSubjectVo::getSubjectId, o -> o, (key1, key2) -> key2));
        return examSubjectMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateEnterpriseExamineeArchive(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) throws Exception {
        if (StringUtils.isEmpty(queryExamineeGradeVo.getExamId())) {
            throw new CustomException("考试ID不能为空！");
        }
        Boolean relationZs = Boolean.FALSE;
        // 查询考试是否关联证书
        ZsInfoVO zsInfoVO = zsInfoService.getZsInfoByDataSourceToExam(queryExamineeGradeVo.getExamId());
        if (null != zsInfoVO) {
            relationZs = Boolean.TRUE;
            // 证书是否发布
            if (CertificateStatusEnums.PUBLISHED.getCode().equals(zsInfoVO.getCertificateStatus())) {
                throw new CustomException("证书已发布，不允许进行归档操作！");
            }
        }
        //考试组归档
        // 判断考试是否存在
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(queryExamineeGradeVo.getExamId());
        if (examInfo == null || StringUtils.isEmpty(examInfo.getExamNameConfigId())) {
            throw new CustomException("所选考试不存在！");
        }
        if ("1".equals(queryExamineeGradeVo.getTickFlag())) {
            //归档总成绩
            if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
                //考数组合并考试
                if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
                    Map<String, Object> parms = new HashMap<>();
                    parms.put("relationId", queryExamineeGradeVo.getExamId());
                    List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
                    List<String> examIds = new ArrayList<>();
                    for (ExamInfoVo examInfoVo : examInfoVos) {
                        examIds.add(examInfoVo.getId());
                        enterpriseExamineeInfoMapper.updateGroupArchiveByExamId(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), examInfoVo.getId());

                    }
                    List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds.toArray(new String[examIds.size()]));
                    for (ExamSubjectVo examSubjectVo : examSubjectVos) {
                        enterpriseExamineeSubjectGradeMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), examSubjectVo.getExamInfoId(), examSubjectVo.getSubjectId());

                    }

                } else {
                    enterpriseExamineeInfoMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId());
                    enterpriseExamineeSubjectGradeMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());

                }

            } else {//归档科目成绩
                enterpriseExamineeSubjectGradeMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());
            }
            return 1;
        }
        if (null == queryExamineeGradeVo.getExamineeIds() || queryExamineeGradeVo.getExamineeIds().length < 1) {
            throw new CustomException("考生ID不能为空！");
        }

        //归档总成绩
        if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
            //考数组合并考试
            if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
                Map<String, Object> parms = new HashMap<>();
                parms.put("relationId", queryExamineeGradeVo.getExamId());
                List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
                String[] examIds = examInfoVos.stream().map(e -> e.getId()).collect(Collectors.toSet()).toArray(new String[examInfoVos.size()]);
                List<EnterpriseExamineeInfo> enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryExamineeGradeVo.getExamineeIds()));
                //查询考试组另外考试的学生
                QueryEnterpriseExamineeGradeVo queryExaminee = new QueryEnterpriseExamineeGradeVo();
                queryExaminee.setExamIds(examIds);
                queryExaminee.setIdCards(enterpriseExamineeInfo.stream().filter(e -> StringUtils.isNotEmpty(e.getIdcard())).map(e -> e.getIdcard()).collect(Collectors.toSet()).toArray(new String[enterpriseExamineeInfo.size()]));
                queryExaminee.setExamineeNames(enterpriseExamineeInfo.stream().filter(e -> StringUtils.isNotEmpty(e.getName())).map(e -> e.getName()).collect(Collectors.toSet()).toArray(new String[enterpriseExamineeInfo.size()]));
                List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectExamineeExamList(queryExaminee);
                Set<String> examineeIds = enterpriseExamineeInfos.stream().map(e -> e.getId()).collect(Collectors.toSet());
                enterpriseExamineeInfoMapper.updateGroupArchiveByIds(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), examineeIds.toArray(new String[examineeIds.size()]));

                List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds);
                for (ExamSubjectVo examSubjectVo : examSubjectVos) {
                    enterpriseExamineeSubjectGradeMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), examSubjectVo.getExamInfoId(), examSubjectVo.getSubjectId(), examineeIds.toArray(new String[examineeIds.size()]));

                }
            } else {
                //考试归档
                enterpriseExamineeInfoMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), queryExamineeGradeVo.getExamineeIds());
                enterpriseExamineeSubjectGradeMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId(), queryExamineeGradeVo.getExamineeIds());
            }
        } else {//归档科目成绩
            enterpriseExamineeSubjectGradeMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_Y, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId(), queryExamineeGradeVo.getExamineeIds());
        }
        // 如果关联证书同步证书信息
        if (relationZs) {
            // 查询关联证书的列表
            List<ZsInfoVO> zsInfoVOS = zsInfoService.listZsInfoByDataSourceToExam(queryExamineeGradeVo.getExamId());
            for (ZsInfoVO infoVO : zsInfoVOS) {
                // 证书授予对象
                Integer certificateGrantObject = infoVO.getCertificateGrantObject();
                // 全部已归档考生
                if (null != certificateGrantObject && CertificateGrantObjectEnums.ARCHIVED.getCode().equals(certificateGrantObject)) {
                    archiveZsexamineeInfo(queryExamineeGradeVo, infoVO);
                }
                if (null != certificateGrantObject && CertificateGrantObjectEnums.EXAM_GRADE.getCode().equals(certificateGrantObject)) {
                    archiveZsexamineeInfo(queryExamineeGradeVo, infoVO, infoVO.getExamScoreLines());
                }
            }
        }
        return 1;

    }

    private void archiveZsexamineeInfo(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo, ZsInfoVO zsInfoVO, String examScoreLines) {
        List<EnterpriseExamineeInfo> examineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryExamineeGradeVo.getExamineeIds()));
        if (CollectionUtils.isEmpty(examineeInfos)) {
            return;
        }

        // 考试结果
        EnterpriseScoreLineListParam result = enterpriseExamScoreLineSettingService.getScoreLineVOList(queryExamineeGradeVo.getExamId(), "0", null);
        if (CollectionUtils.isEmpty(result.getScoreLineData())) {
            return;
        }
        List<String> qualifiedStatus = new ArrayList<String>();
        List<String> regionNames = new ArrayList<String>();
        if (CommonEnums.SCORE_LINE_TYPE_0.getCode().equals(result.getType()) || CommonEnums.SCORE_LINE_TYPE_1.getCode().equals(result.getType())) {
            List<String> scoreIdList = Arrays.asList(zsInfoVO.getExamScoreLines().split(","));
            if (CollectionUtils.isNotEmpty(scoreIdList)) {
                for (String scoreId : scoreIdList) {
                    qualifiedStatus.add(scoreId);
                }
            }
        }

        if (CommonEnums.SCORE_LINE_TYPE_2.getCode().equals(result.getType())) {
            List<String> scoreIdList = Arrays.asList(zsInfoVO.getExamScoreLines().split(","));
            if (CollectionUtils.isNotEmpty(scoreIdList)) {
                for (String scoreId : scoreIdList) {
                    regionNames.add(scoreId);
                }
            }
        }

        List<EnterpriseExamineeInfo> needList = new ArrayList<EnterpriseExamineeInfo>();
        for (EnterpriseExamineeInfo info : examineeInfos) {
            if (StringUtils.isEmpty(info.getIdcard()) && StringUtils.isEmpty(info.getAdmissionNo())) {
                continue;
            }
            if (CollectionUtils.isNotEmpty(qualifiedStatus)) {
                if (qualifiedStatus.contains(info.getQualifiedStatus())) {
                    needList.add(info);
                }
            }
            if (CollectionUtils.isNotEmpty(regionNames)) {
                if (regionNames.contains(info.getRegionName())) {
                    needList.add(info);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(needList)) {
            // 考生与证书关联关系
            List<EnterpriseExamineeCertificateRelation> examineeCertificateRelationSaveList = new ArrayList<>();
            List<ZsExamineeInfo> zsList = new ArrayList<>();
            for (EnterpriseExamineeInfo enterpriseExamineeInfo : needList) {
                // 获取考生的准考证号 和 idcard
                String admissionNo = enterpriseExamineeInfo.getAdmissionNo();
                String idcardNo = enterpriseExamineeInfo.getIdcard();
                // 查询证书考生是否存在
                ZsExamineeInfo oldZsExamineeInfo = zsExamineeInfoMapper.queryZsExamineeByExamId(queryExamineeGradeVo.getExamId(), admissionNo, idcardNo);
                if (null == oldZsExamineeInfo) {
                    LocalDateTime time = LocalDateTime.now();
                    // 做考生新增
                    log.debug("# 成绩归档，生成证书考生：{}", enterpriseExamineeInfo.getName());
                    ZsExamineeInfo zsExamineeInfo = new ZsExamineeInfo();
                    zsExamineeInfo.setId(UUIDUtils.newSortUUID());
                    zsExamineeInfo.setZsId(zsInfoVO.getId());
                    zsExamineeInfo.setExamineeName(enterpriseExamineeInfo.getName());
                    zsExamineeInfo.setExamineeSex(enterpriseExamineeInfo.getSex());
                    zsExamineeInfo.setIdentificationType(IdentificationType.IDCARD.getCode());
                    zsExamineeInfo.setIdentificationNo(enterpriseExamineeInfo.getIdcard());
                    zsExamineeInfo.setAdmissionNo(enterpriseExamineeInfo.getAdmissionNo());
                    zsExamineeInfo.setCertificateSubject(zsInfoVO.getCertificateSubject());
                    zsExamineeInfo.setCertificateSubjectName(zsInfoVO.getCertificateSubjectDesc());
                    zsExamineeInfo.setCertificateLevel(zsInfoVO.getCertificateLevel());
                    zsExamineeInfo.setCertificateLevelDesc(zsInfoVO.getCertificateLevelDesc());
                    zsExamineeInfo.setCertificateProvideStatus(CertificateProvideStatusEnums.UNPROVIDED.getCode());
                    zsExamineeInfo.setCreateBy(zsInfoVO.getCreateBy());
                    zsExamineeInfo.setUpdateBy(zsInfoVO.getUpdateBy());
                    zsExamineeInfo.setCreateDate(time);
                    zsExamineeInfo.setUpdateDate(time);
                    zsExamineeInfo.setDelFlag(false);

                    // 企业考生证书关联
                    EnterpriseExamineeCertificateRelation examineeCertificateRelation = EnterpriseExamineeCertificateRelation
                            .builder()
                            .id(UUIDUtils.newSortUUID())
                            .enterpriseExamineeInfoId(enterpriseExamineeInfo.getId())
                            .examInfoId(enterpriseExamineeInfo.getExamId())
                            .zsInfoId(zsInfoVO.getId())
                            .zsExamineeInfoId(zsExamineeInfo.getId())
                            .build();

                    examineeCertificateRelationSaveList.add(examineeCertificateRelation);
                    zsList.add(zsExamineeInfo);
                }
            }
            if (CollectionUtils.isNotEmpty(zsList)) {
                iZsExamineeInfoService.saveBatch(zsList);
                // 如果与成绩发布关联同步关系
                zsInfoService.synchronizeListExamineeCertificateRelation(zsInfoVO, examineeCertificateRelationSaveList);
            }
        }

    }


    private void cancelArchiveZsexamineeInfo(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo, ZsInfoVO zsInfoVO, String examScoreLines) {
        List<EnterpriseExamineeInfo> examineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryExamineeGradeVo.getExamineeIds()));
        if (CollectionUtils.isEmpty(examineeInfos)) {
            return;
        }

        // 考试结果
        EnterpriseScoreLineListParam result = enterpriseExamScoreLineSettingService.getScoreLineVOList(queryExamineeGradeVo.getExamId(), "0", null);
        if (CollectionUtils.isEmpty(result.getScoreLineData())) {
            return;
        }
        List<String> qualifiedStatus = new ArrayList<String>();
        List<String> regionNames = new ArrayList<String>();
        if (CommonEnums.SCORE_LINE_TYPE_0.getCode().equals(result.getType()) || CommonEnums.SCORE_LINE_TYPE_1.getCode().equals(result.getType())) {
            List<String> scoreIdList = Arrays.asList(zsInfoVO.getExamScoreLines().split(","));
            if (CollectionUtils.isNotEmpty(scoreIdList)) {
                for (String scoreId : scoreIdList) {
                    qualifiedStatus.add(scoreId);
                }
            }
        }

        if (CommonEnums.SCORE_LINE_TYPE_2.getCode().equals(result.getType())) {
            List<String> scoreIdList = Arrays.asList(zsInfoVO.getExamScoreLines().split(","));
            if (CollectionUtils.isNotEmpty(scoreIdList)) {
                for (String scoreId : scoreIdList) {
                    regionNames.add(scoreId);
                }
            }
        }

        List<EnterpriseExamineeInfo> needList = new ArrayList<EnterpriseExamineeInfo>();
        for (EnterpriseExamineeInfo info : examineeInfos) {
            if (StringUtils.isEmpty(info.getIdcard()) && StringUtils.isEmpty(info.getAdmissionNo())) {
                continue;
            }
            if (CollectionUtils.isNotEmpty(qualifiedStatus)) {
                if (qualifiedStatus.contains(info.getQualifiedStatus())) {
                    needList.add(info);
                }
            }
            if (CollectionUtils.isNotEmpty(regionNames)) {
                if (regionNames.contains(info.getRegionName())) {
                    needList.add(info);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(needList)) {
            List<ZsExamineeInfo> zsList = new ArrayList<>();
            for (EnterpriseExamineeInfo enterpriseExamineeInfo : needList) {
                // 获取考生的准考证号 和 idcard
                String admissionNo = enterpriseExamineeInfo.getAdmissionNo();
                String idcardNo = enterpriseExamineeInfo.getIdcard();
                // 查询证书考生是否存在
                ZsExamineeInfo oldZsExamineeInfo = zsExamineeInfoMapper.queryZsExamineeByExamId(queryExamineeGradeVo.getExamId(), admissionNo, idcardNo);
                if (null != oldZsExamineeInfo) {
                    oldZsExamineeInfo.setDelFlag(true);
                    oldZsExamineeInfo.setUpdateDate(LocalDateTime.now());
                    zsList.add(oldZsExamineeInfo);
                }
            }
            if (CollectionUtils.isNotEmpty(zsList)) {
                iZsExamineeInfoService.updateBatchById(zsList);
            }

            String[] examineeIds = needList.stream()
                    .map(EnterpriseExamineeInfo::getId)
                    .toArray(String[]::new);
            // 删除考生与证书的绑定关系
            enterpriseExamineeCertificateRelationService.removeByExamineeInfoIds(examineeIds);
        }

    }

    /**
     * 归档考生
     *
     * @param queryExamineeGradeVo
     * @param zsInfoVO
     */
    private void archiveZsexamineeInfo(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo, ZsInfoVO zsInfoVO) {
        // 查询所有的考生
        String[] examineeIds = queryExamineeGradeVo.getExamineeIds();
        List<EnterpriseExamineeInfo> examineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(examineeIds));
        if (CollectionUtils.isNotEmpty(examineeInfos)) {
            // 考生与证书关联关系
            List<EnterpriseExamineeCertificateRelation> examineeCertificateRelationSaveList = new ArrayList<>();
            // 证书考生
            List<ZsExamineeInfo> zsList = new ArrayList<>();
            for (EnterpriseExamineeInfo enterpriseExamineeInfo : examineeInfos) {
                // 获取考生的准考证号  和 idcard
                String admissionNo = enterpriseExamineeInfo.getAdmissionNo();
                String idcardNo = enterpriseExamineeInfo.getIdcard();
                // 查询证书考生是否存在
                ZsExamineeInfo oldZsExamineeInfo = zsExamineeInfoMapper.queryZsExamineeByExamId(queryExamineeGradeVo.getExamId(), admissionNo, idcardNo);
                if (null == oldZsExamineeInfo) {
                    LocalDateTime time = LocalDateTime.now();
                    // 做考生新增
                    log.debug("# 成绩归档，生成证书考生：{}", enterpriseExamineeInfo.getName());
                    ZsExamineeInfo zsExamineeInfo = new ZsExamineeInfo();
                    zsExamineeInfo.setId(UUIDUtils.newSortUUID());
                    zsExamineeInfo.setZsId(zsInfoVO.getId());
                    zsExamineeInfo.setExamineeName(enterpriseExamineeInfo.getName());
                    zsExamineeInfo.setExamineeSex(enterpriseExamineeInfo.getSex());
                    zsExamineeInfo.setIdentificationType(IdentificationType.IDCARD.getCode());
                    zsExamineeInfo.setIdentificationNo(enterpriseExamineeInfo.getIdcard());
                    zsExamineeInfo.setAdmissionNo(enterpriseExamineeInfo.getAdmissionNo());
                    zsExamineeInfo.setCertificateSubject(zsInfoVO.getCertificateSubject());
                    zsExamineeInfo.setCertificateSubjectName(zsInfoVO.getCertificateSubjectDesc());
                    zsExamineeInfo.setCertificateLevel(zsInfoVO.getCertificateLevel());
                    zsExamineeInfo.setCertificateLevelDesc(zsInfoVO.getCertificateLevelDesc());
                    zsExamineeInfo.setCertificateProvideStatus(CertificateProvideStatusEnums.UNPROVIDED.getCode());
                    zsExamineeInfo.setCreateBy(zsInfoVO.getCreateBy());
                    zsExamineeInfo.setUpdateBy(zsInfoVO.getUpdateBy());
                    zsExamineeInfo.setCreateDate(time);
                    zsExamineeInfo.setUpdateDate(time);
                    zsExamineeInfo.setDelFlag(false);

                    // 企业考生证书关联
                    EnterpriseExamineeCertificateRelation examineeCertificateRelation = EnterpriseExamineeCertificateRelation
                            .builder()
                            .id(UUIDUtils.newSortUUID())
                            .enterpriseExamineeInfoId(enterpriseExamineeInfo.getId())
                            .examInfoId(enterpriseExamineeInfo.getExamId())
                            .zsInfoId(zsInfoVO.getId())
                            .zsExamineeInfoId(zsExamineeInfo.getId())
                            .build();

                    examineeCertificateRelationSaveList.add(examineeCertificateRelation);
                    zsList.add(zsExamineeInfo);
                }
            }
            if (CollectionUtils.isNotEmpty(zsList)) {
                iZsExamineeInfoService.saveBatch(zsList);
                // 如果与成绩发布关联同步关系
                zsInfoService.synchronizeListExamineeCertificateRelation(zsInfoVO, examineeCertificateRelationSaveList);
            }
        }
    }


    private void cancelArchiveZsexamineeInfo(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo, ZsInfoVO zsInfoVO) {
        // 查询所有的考生
        String[] examineeIds = queryExamineeGradeVo.getExamineeIds();
        List<EnterpriseExamineeInfo> examineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(examineeIds));
        if (CollectionUtils.isNotEmpty(examineeInfos)) {
            List<ZsExamineeInfo> zsList = new ArrayList<>();
            for (EnterpriseExamineeInfo enterpriseExamineeInfo : examineeInfos) {
                // 获取考生的准考证号 和 idcard
                String admissionNo = enterpriseExamineeInfo.getAdmissionNo();
                String idcardNo = enterpriseExamineeInfo.getIdcard();
                // 查询证书考生是否存在
                ZsExamineeInfo oldZsExamineeInfo = zsExamineeInfoMapper.queryZsExamineeByExamId(queryExamineeGradeVo.getExamId(), admissionNo, idcardNo);
                if (null != oldZsExamineeInfo) {
                    oldZsExamineeInfo.setDelFlag(Boolean.TRUE);
                    oldZsExamineeInfo.setUpdateDate(LocalDateTime.now());
                    zsList.add(oldZsExamineeInfo);
                }
            }
            if (CollectionUtils.isNotEmpty(zsList)) {
                iZsExamineeInfoService.updateBatchById(zsList);
            }
        }
        // 删除考生与证书的绑定关系
        enterpriseExamineeCertificateRelationService.removeByExamineeInfoIds(examineeIds);
    }

    @Override
    public void insertBatchEnterpriseExamineeGrade(List<EnterpriseExamineeInfoImportVo> list) {
        int maxImport = IEnterpriseExamineeGradeImportService.MAX_IMPORT;
        log.info("插入成绩信息Begin...总共插入{}条数据,每次插入{}条成绩信息", list.size(), maxImport);
        //
        int insertNum = 1;
        // 总共需要插入次数
        int totalInsertTimes = list.size() / IEnterpriseExamineeGradeImportService.MAX_IMPORT + 1;
        log.info("插入成绩信息,总共需要插入{}次", totalInsertTimes);
        // 需要插入的成绩信息和科目成绩信息
        List<EnterpriseExamineeInfo> insertExamineeInfoList = new ArrayList<>();
        List<EnterpriseExamineeSubjectGrade> insertExamineeSubjectGradeList = new ArrayList<>();
        // 当前插入次数
        int curInsertTime = 1;
        for (EnterpriseExamineeInfoImportVo examineeGradeVo : list) {
            insertExamineeInfoList.add(examineeGradeVo.getEnterpriseExamineeInfo());
            insertExamineeSubjectGradeList.addAll(examineeGradeVo.getEnterpriseExamineeGradeList());

            if (insertNum == maxImport) {
                // 执行插入
                enterpriseExamineeInfoMapper.insertBatchEnterpriseExamineeInfo(insertExamineeInfoList);
                enterpriseExamineeSubjectGradeMapper.insertBatchEnterpriseExamineeSubjectGrade(insertExamineeSubjectGradeList);
                insertExamineeInfoList.clear();
                insertExamineeSubjectGradeList.clear();
                insertNum = 0;
                curInsertTime++;
            } else {
                // 最后一次插入数据如果小于200条也插入
                if (((curInsertTime - 1) * maxImport + insertNum) == list.size()) {
                    enterpriseExamineeInfoMapper.insertBatchEnterpriseExamineeInfo(insertExamineeInfoList);
                    enterpriseExamineeSubjectGradeMapper.insertBatchEnterpriseExamineeSubjectGrade(insertExamineeSubjectGradeList);
                }
            }
            insertNum++;
        }
        log.info("插入成绩信息End...");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshEnterpriseExamineeQualified(String examId) {
        log.info("执行refreshEnterpriseExamineeQualified开始...");
        //查询考试设置的科目分数线
//        Integer pageSize = 200;
//        Integer pageNum = 1;
        //处理考生的合格
//        EnterpriseExamineeInfo param = new EnterpriseExamineeInfo();
//        param.setExamId(examId);
//        PageHelper.startPage(pageNum, pageSize);
//        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(param);
//        if (CollectionUtils.isEmpty(enterpriseExamineeInfos)) {
//            return;
//        }
        //查询分页考生的所有科目
        List<EnterpriseScoreLineSaveParam> scoreLineSettings = enterpriseExamScoreLineSettingService.getScoreLineList(examId, null, null);
        Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getDimension()));
        List<EnterpriseScoreLineSaveParam> examScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_0.getCode());
        //设置分数线 单科
        Map<String, List<ScoreLineItem>> examSngleScoreLineItemMap = getSngleScoreLineItemMap(examScoreLineSettings);
        //设置分数线 复合
        Map<String, List<ScoreLineItem>> examCompositeScoreLineItemMap = getCompositeScoreLineItemMap(examScoreLineSettings);
        //区间分数线
        List<ScoreLineItem> examRegionScoreLineItemList = getRegionScoreLineItems(examScoreLineSettings);

//        PageInfo<EnterpriseExamineeInfo> pageInfo = new PageInfo(enterpriseExamineeInfos);
        executeQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, examId);
        executeRegionname(examRegionScoreLineItemList, examId);
//        for (pageNum = 2; pageNum < pageInfo.getPages(); pageNum++) {
//            PageHelper.startPage(pageNum, pageSize);
//            enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(param);
//            executeQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, enterpriseExamineeInfos);
//            executeRegionname(examRegionScoreLineItemList, enterpriseExamineeInfos);
//        }
        log.info("执行refreshEnterpriseExamineeQualified结束...");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshEnterpriseExamineeSubjectQualified(String examId) {
        log.info("执行refreshEnterpriseExamineeSubjectQualified开始...");
        //查询考试设置的科目分数线
//        Integer pageSize = 200;
//        Integer pageNum = 1;
        //处理考生的合格
//        EnterpriseExamineeInfo param = new EnterpriseExamineeInfo();
//        param.setExamId(examId);
//        PageHelper.startPage(pageNum, pageSize);
//        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(param);
//        if (CollectionUtils.isEmpty(enterpriseExamineeInfos)) {
//            return;
//        }
        //查询考试设置的科目分数线
        List<EnterpriseScoreLineSaveParam> scoreLineSettings = enterpriseExamScoreLineSettingService.getScoreLineList(examId, null, null);
        // 科目分数线
        Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getDimension()));
        List<EnterpriseScoreLineSaveParam> subjectScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_1.getCode());
        Map<String, List<ScoreLineItem>> subjectSngleScoreLineItemMap = getSngleScoreLineItemMap(subjectScoreLineSettings);
        List<ScoreLineItem> subjectRegionScoreLineItemList = getRegionScoreLineItems(subjectScoreLineSettings);
//        PageInfo<EnterpriseExamineeInfo> pageInfo = new PageInfo(enterpriseExamineeInfos);
        executeSubjectQualifiedStatus(examId, subjectSngleScoreLineItemMap);
        executeSubjectRegionname(examId, subjectRegionScoreLineItemList);
//        for (pageNum = 2; pageNum < pageInfo.getPages(); pageNum++) {
//            PageHelper.startPage(pageNum, pageSize);
//            enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(param);
//            executeSubjectQualifiedStatus(enterpriseExamineeInfos, subjectSngleScoreLineItemMap);
//            executeSubjectRegionname(enterpriseExamineeInfos, subjectRegionScoreLineItemList);
//        }

        log.info("执行refreshEnterpriseExamineeSubjectQualified结束...");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshEnterpriseExamineeQualified(String examId, String examineeId) {
        EnterpriseExamineeInfo enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoById(examineeId);
        if (null == enterpriseExamineeInfo || !enterpriseExamineeInfo.getExamId().equals(examId)) {
            return;
        }
        EnterpriseExamineeSubjectGrade enterpriseExamineeSubjectGrade = new EnterpriseExamineeSubjectGrade();
        enterpriseExamineeSubjectGrade.setExamineeId(enterpriseExamineeInfo.getId());
        List<EnterpriseExamineeSubjectGrade> grades = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeSubjectGradeList(enterpriseExamineeSubjectGrade);
        if (CollectionUtils.isEmpty(grades)) {
            return;
        }
        //查询分页考生的所有科目
        List<EnterpriseScoreLineSaveParam> scoreLineSettings = enterpriseExamScoreLineSettingService.getScoreLineList(examId, null, null);
        Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getDimension()));
        List<EnterpriseScoreLineSaveParam> examScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_0.getCode());
        //设置分数线 单科
        Map<String, List<ScoreLineItem>> examSngleScoreLineItemMap = getSngleScoreLineItemMap(examScoreLineSettings);
        //设置分数线 复合
        Map<String, List<ScoreLineItem>> examCompositeScoreLineItemMap = getCompositeScoreLineItemMap(examScoreLineSettings);
        //区间分数线
        List<ScoreLineItem> examRegionScoreLineItemList = getRegionScoreLineItems(examScoreLineSettings);

        List<EnterpriseScoreLineSaveParam> subjectScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_1.getCode());
        Map<String, List<ScoreLineItem>> subjectSngleScoreLineItemMap = getSngleScoreLineItemMap(subjectScoreLineSettings);
        List<ScoreLineItem> subjectRegionScoreLineItemList = getRegionScoreLineItems(subjectScoreLineSettings);

        enterpriseExamineeInfo.setRegionName(getExamRegionName(examRegionScoreLineItemList, grades));
        enterpriseExamineeInfo.setQualifiedStatus(getExamQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, grades));
        enterpriseExamineeInfoMapper.updateEnterpriseExamineeInfo(enterpriseExamineeInfo);
        for (EnterpriseExamineeSubjectGrade grade : grades) {
            grade.setRegionName(getSubjectRegionName(subjectRegionScoreLineItemList, grade));
            grade.setQualifiedStatus(getGradeQualifiedStatus(grade, subjectSngleScoreLineItemMap));
            enterpriseExamineeSubjectGradeMapper.updateEnterpriseExamineeSubjectGrade(grade);
        }
    }

    /**
     * 执行更新考试区间操作
     *
     * @param examRegionScoreLineItemList
     * @param
     */
    private void executeRegionname(List<ScoreLineItem> examRegionScoreLineItemList, String examId) {

        if (CollectionUtils.isEmpty(examRegionScoreLineItemList)) {
            return;
        }
        List<String> examIds = new ArrayList<>();
        examIds.add(examId);
        List<EnterpriseExamineeSubjectGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectExamineeSubjectGradeByExamIds(examIds.toArray(new String[examIds.size()]));

        if (CollectionUtils.isEmpty(gradeVos)) {
            return;
        }
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> examineeSubjectGradeMap = gradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));

        //处理考试区间业务逻辑
        List<EnterpriseExamineeSubjectGradeVo> subjectGradeVos = new ArrayList<>(examineeSubjectGradeMap.size());
        for (String key : examineeSubjectGradeMap.keySet()) {
            List<EnterpriseExamineeSubjectGrade> allGradeList = new ArrayList<>(examineeSubjectGradeMap.size());
            for (EnterpriseExamineeSubjectGradeVo vo : examineeSubjectGradeMap.get(key)) {
                EnterpriseExamineeSubjectGrade subjectGrade = new EnterpriseExamineeSubjectGrade();
                subjectGrade.setSubjectId(vo.getSubjectId());
                subjectGrade.setScore(vo.getScore());
                allGradeList.add(subjectGrade);
            }
            String eegionName = getExamRegionName(examRegionScoreLineItemList, allGradeList);
            EnterpriseExamineeSubjectGradeVo subjectGradeVo = new EnterpriseExamineeSubjectGradeVo();
            subjectGradeVo.setExamineeId(key);
            subjectGradeVo.setRegionName(eegionName);
            subjectGradeVos.add(subjectGradeVo);

        }
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> examineeMap = subjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getRegionName()));
        for (String key : examineeMap.keySet()) {
            List<EnterpriseExamineeSubjectGradeVo> examinees = examineeMap.get(key);
            Set<String> ids = examinees.stream().map(e -> e.getExamineeId()).collect(Collectors.toSet());
            enterpriseExamineeInfoMapper.updateRegionnameByIds(key, ids.toArray(new String[ids.size()]));
        }

    }

    /**
     * 执行更新考试合格操作
     *
     * @param sngleScoreLineItemMap
     * @param compositeScoreLineItemMap
     * @param
     */
    private void executeQualifiedStatus(Map<String, List<ScoreLineItem>> sngleScoreLineItemMap, Map<String, List<ScoreLineItem>> compositeScoreLineItemMap, String examId) {

        if (MapUtils.isEmpty(sngleScoreLineItemMap) && MapUtils.isEmpty(compositeScoreLineItemMap)) {
            return;
        }
        List<String> examIds = new ArrayList<>();
        examIds.add(examId);
        List<EnterpriseExamineeSubjectGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectExamineeSubjectGradeByExamIds(examIds.toArray(new String[examIds.size()]));
        if (CollectionUtils.isEmpty(gradeVos)) {
            return;
        }
        List<EnterpriseExamineeSubjectGradeVo> subjectGradeVos = new ArrayList<>(gradeVos.size());
        //处理考试合格业务逻辑
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> gradeMap = gradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));
        for (String key : gradeMap.keySet()) {
            List<EnterpriseExamineeSubjectGrade> allGradeList = new ArrayList<>(gradeMap.get(key).size());
            for (EnterpriseExamineeSubjectGradeVo vo : gradeMap.get(key)) {
                EnterpriseExamineeSubjectGrade subjectGrade = new EnterpriseExamineeSubjectGrade();
                subjectGrade.setSubjectId(vo.getSubjectId());
                subjectGrade.setScore(vo.getScore());
                allGradeList.add(subjectGrade);
            }
            String qualifiedStatus = getExamQualifiedStatus(sngleScoreLineItemMap, compositeScoreLineItemMap, allGradeList);
            //未设置分数线考试成绩返回为"",合格返回Y，不合格发货N
            EnterpriseExamineeSubjectGradeVo subjectGradeVo = new EnterpriseExamineeSubjectGradeVo();
            subjectGradeVo.setExamineeId(key);
            subjectGradeVo.setQualifiedStatus(qualifiedStatus);
            subjectGradeVos.add(subjectGradeVo);
        }
        if (CollectionUtils.isEmpty(subjectGradeVos)) {
            return;
        }
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = subjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getQualifiedStatus()));

        //合格
        if (CollectionUtils.isNotEmpty(subjectGradeMap.get(CommonEnums.QUALIFIED_STATUS_Y.getCode()))) {
            List<String> ids = subjectGradeMap.get(CommonEnums.QUALIFIED_STATUS_Y.getCode()).stream().map(e -> e.getExamineeId()).collect(Collectors.toList());
            enterpriseExamineeInfoMapper.updateQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_Y.getCode(), ids.toArray(new String[ids.size()]));
        }
        //不合格
        if (CollectionUtils.isNotEmpty(subjectGradeMap.get(CommonEnums.QUALIFIED_STATUS_N.getCode()))) {
            List<String> unids = subjectGradeMap.get(CommonEnums.QUALIFIED_STATUS_N.getCode()).stream().map(e -> e.getExamineeId()).collect(Collectors.toList());
            enterpriseExamineeInfoMapper.updateQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_N.getCode(), unids.toArray(new String[unids.size()]));

        }
        if (CollectionUtils.isNotEmpty(subjectGradeMap.get(CommonEnums.QUALIFIED_STATUS_D.getCode()))) {
            List<String> dids = subjectGradeMap.get(CommonEnums.QUALIFIED_STATUS_D.getCode()).stream().map(e -> e.getExamineeId()).collect(Collectors.toList());
            enterpriseExamineeInfoMapper.updateQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_D.getCode(), dids.toArray(new String[dids.size()]));
        }

    }

    /**
     * 执行更新科目合格操作
     *
     * @param examId
     */
    private void executeSubjectQualifiedStatus(String examId, Map<String, List<ScoreLineItem>> subjectSngleScoreLineItemMap) {
        if (MapUtils.isEmpty(subjectSngleScoreLineItemMap)) {
            return;
        }
        List<String> examIds = new ArrayList<>();
        examIds.add(examId);
        List<EnterpriseExamineeSubjectGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectExamineeSubjectGradeByExamIds(examIds.toArray(new String[examIds.size()]));
        if (CollectionUtils.isEmpty(gradeVos)) {
            return;
        }
        List<String> gradeIds = new ArrayList<>();
        List<String> unGradeIds = new ArrayList<>();
        List<String> defGradeIds = new ArrayList<>();
        //处理科目合格业务
        for (EnterpriseExamineeSubjectGradeVo gradeVo : gradeVos) {
            EnterpriseExamineeSubjectGrade grade = new EnterpriseExamineeSubjectGrade();
            grade.setId(gradeVo.getId());
            grade.setSubjectId(gradeVo.getSubjectId());
            grade.setScore(gradeVo.getScore());
            //未设置分数线考试成绩返回为""
            String qualifiedStatus = getGradeQualifiedStatus(grade, subjectSngleScoreLineItemMap);
            grade.setStemId(gradeVo.getSubjectId());
            //设置分数线考试成绩
            if (CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(qualifiedStatus)) {
                gradeIds.add(grade.getId());
            } else if (CommonEnums.QUALIFIED_STATUS_N.getCode().equals(qualifiedStatus)) {
                unGradeIds.add(grade.getId());
            } else {
                defGradeIds.add(grade.getId());
            }

        }
        if (CollectionUtils.isNotEmpty(gradeIds)) {
            enterpriseExamineeSubjectGradeMapper.updateQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_Y.getCode(), gradeIds.toArray(new String[gradeIds.size()]));
        }
        if (CollectionUtils.isNotEmpty(unGradeIds)) {
            enterpriseExamineeSubjectGradeMapper.updateQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_N.getCode(), unGradeIds.toArray(new String[unGradeIds.size()]));
        }
        if (CollectionUtils.isNotEmpty(defGradeIds)) {
            enterpriseExamineeSubjectGradeMapper.updateQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_D.getCode(), defGradeIds.toArray(new String[defGradeIds.size()]));
        }
    }


    /**
     * 执行更新科目分数区间操作
     *
     * @param examId
     */
    private void executeSubjectRegionname(String examId, List<ScoreLineItem> subjectRegionScoreLineItemList) {
        if (CollectionUtils.isEmpty(subjectRegionScoreLineItemList)) {
            return;
        }
        List<String> examIds = new ArrayList<>();
        examIds.add(examId);
        List<EnterpriseExamineeSubjectGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectExamineeSubjectGradeByExamIds(examIds.toArray(new String[examIds.size()]));
        if (CollectionUtils.isEmpty(gradeVos)) {
            return;
        }
        List<EnterpriseExamineeSubjectGrade> grades = new ArrayList<>(gradeVos.size());
        //处理科目区间业务
        for (EnterpriseExamineeSubjectGradeVo gradeVo : gradeVos) {
            EnterpriseExamineeSubjectGrade grade = new EnterpriseExamineeSubjectGrade();
            grade.setId(gradeVo.getId());
            grade.setSubjectId(gradeVo.getSubjectId());
            grade.setScore(gradeVo.getScore());
            //未设置分数线考试成绩返回为""
            String regionname = getSubjectRegionName(subjectRegionScoreLineItemList, grade);
            grade.setStemId(gradeVo.getSubjectId());
            grade.setRegionName(regionname);
            grades.add(grade);

        }
        Map<String, List<EnterpriseExamineeSubjectGrade>> subjectGradeMap = grades.stream().collect(Collectors.groupingBy(c -> c.getRegionName()));
        for (String key : subjectGradeMap.keySet()) {
            List<EnterpriseExamineeSubjectGrade> subjectGrades = subjectGradeMap.get(key);
            Set<String> gradeIds = subjectGrades.stream().map(EnterpriseExamineeSubjectGrade -> EnterpriseExamineeSubjectGrade.getId()).collect(Collectors.toSet());
            enterpriseExamineeSubjectGradeMapper.updateRegionnameByIds(key, gradeIds.toArray(new String[gradeIds.size()]));
        }
    }

    /**
     * 复合分数线Map
     *
     * @param scoreLineSettings
     * @return
     */
    @Override
    public Map<String, List<ScoreLineItem>> getCompositeScoreLineItemMap(List<EnterpriseScoreLineSaveParam> scoreLineSettings) {
        Map<String, List<ScoreLineItem>> compositeScoreLineItemMap = null;
        List<ScoreLineItem> compositeScoreLineItems = new ArrayList<>(4);
        if (CollectionUtils.isNotEmpty(scoreLineSettings)) {
            //分数线类型为单分组
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getType()));

            //根据复合分组
            if (CollectionUtils.isNotEmpty(scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_1.getCode()))) {
                for (EnterpriseScoreLineSaveParam lineSaveParam : scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_1.getCode())) {
                    compositeScoreLineItems.addAll(lineSaveParam.getScoreLineItems());
                }
                compositeScoreLineItemMap = compositeScoreLineItems.stream().collect(Collectors.groupingBy(c -> c.getSettingId()));

            }

        }
        return compositeScoreLineItemMap;
    }


    /**
     * 区间分数线Map
     *
     * @param scoreLineSettings
     * @return
     */
    @Override
    public List<ScoreLineItem> getRegionScoreLineItems(List<EnterpriseScoreLineSaveParam> scoreLineSettings) {
        List<ScoreLineItem> compositeScoreLineItems = null;
        if (CollectionUtils.isNotEmpty(scoreLineSettings)) {
            //分数线类型为单分组
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getType()));
            compositeScoreLineItems = new ArrayList<>(scoreLineSettings.size());
            //根据区间分组
            if (CollectionUtils.isNotEmpty(scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_2.getCode()))) {
                for (EnterpriseScoreLineSaveParam lineSaveParam : scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_2.getCode())) {
                    compositeScoreLineItems.addAll(lineSaveParam.getScoreLineItems());
                }
            }

        }
        return compositeScoreLineItems;
    }

    @Override
    public List<CandidateInfoVo> getExamineeInfo(String examinId, String examineeId) {

        //获取考生的基本信息,如果是同步的，则获取其他信息，如果是系统自带的，则只拼接基础信息
        EnterpriseExamineeInfo enterpriseExamineeInfo = enterpriseExamineeInfoMapper.getExamineeByExamineeIdAndExaminId(examinId, examineeId);
        if (enterpriseExamineeInfo == null) {
            throw new CustomException("暂无考生信息");
        }
        List<CandidateInfoVo> candidateInfoVoList = new ArrayList<>();

        if (enterpriseExamineeInfo.getOrigin().equals(Integer.valueOf(CommonEnums.ORIGIN_1.getCode()))) {
            candidateInfoVoList = candidateInfoMapper.selectExamineeInfo(examinId, examineeId);
            //添加准考证
            CandidateInfoVo candidateInfoVo8 = new CandidateInfoVo("准考证号", enterpriseExamineeInfo.getAdmissionNo(), 8, "1");
            candidateInfoVoList.add(candidateInfoVo8);
        } else if (enterpriseExamineeInfo.getOrigin().equals(Integer.valueOf(CommonEnums.ORIGIN_0.getCode()))) {
            //获取字典项内容
            Map<String, String> sexDataMap = dictDataService.selectDictDataMap("sys_user_sex", "K");
            Map<String, String> educationDataMap = dictDataService.selectDictDataMap("education", "K");
            Map<String, String> subjectDataMap = dictDataService.selectDictDataMap("subject", "K");
            //设置基本内容
            CandidateInfoVo candidateInfoVo1 = new CandidateInfoVo("姓名", enterpriseExamineeInfo.getName(), 2, "1");
            candidateInfoVoList.add(candidateInfoVo1);
            CandidateInfoVo candidateInfoVo2 = new CandidateInfoVo("准考证号", enterpriseExamineeInfo.getAdmissionNo(), 1, "1");
            candidateInfoVoList.add(candidateInfoVo2);
            CandidateInfoVo candidateInfoVo3 = new CandidateInfoVo("身份证号", enterpriseExamineeInfo.getIdcard(), 3, "1");
            candidateInfoVoList.add(candidateInfoVo3);
            CandidateInfoVo candidateInfoVo4 = new CandidateInfoVo("性别", sexDataMap.get(enterpriseExamineeInfo.getSex()), 4, "1");
            candidateInfoVoList.add(candidateInfoVo4);
            CandidateInfoVo candidateInfoVo5 = new CandidateInfoVo("联系方式", enterpriseExamineeInfo.getMobile(), 5, "1");
            candidateInfoVoList.add(candidateInfoVo5);
            CandidateInfoVo candidateInfoVo6 = new CandidateInfoVo("学历", educationDataMap.get(enterpriseExamineeInfo.getEducation()), 6, "1");
            candidateInfoVoList.add(candidateInfoVo6);
            CandidateInfoVo candidateInfoVo7 = new CandidateInfoVo("专业", subjectDataMap.get(enterpriseExamineeInfo.getMajor()), 7, "1");
            candidateInfoVoList.add(candidateInfoVo7);
        }

        //对图片为空的内容进行筛选
        candidateInfoVoList = candidateInfoVoList.stream().filter(candidateInfoVo -> {
            return candidateInfoVo.getFiledType().equals(ExchangeValTypeEnum.EXCHANGE_User_VAL_TYPE_4.getValName())
                    && StringUtils.isEmpty(candidateInfoVo.getConfigValue()) ? false : true;
        }).collect(Collectors.toList());

        //对内容进行排序
        Collections.sort(candidateInfoVoList, new Comparator<CandidateInfoVo>() {
            @Override
            public int compare(CandidateInfoVo o1, CandidateInfoVo o2) {
                if (o1.getOrder() > o2.getOrder()) {
                    return 1;
                }
                return -1;
            }
        });
        return candidateInfoVoList;
    }


    /**
     * 单科分数线Map
     *
     * @param scoreLineSettings
     * @return
     */
    @Override
    public Map<String, List<ScoreLineItem>> getSngleScoreLineItemMap(List<EnterpriseScoreLineSaveParam> scoreLineSettings) {
        Map<String, List<ScoreLineItem>> sngleScoreLineItemMap = null;
        List<ScoreLineItem> sngleScoreLineItems = new ArrayList<>(4);
        if (CollectionUtils.isNotEmpty(scoreLineSettings)) {
            //分数线类型为单分组
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getType()));
            //根据单科分组
            if (CollectionUtils.isNotEmpty(scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_0.getCode()))) {
                for (EnterpriseScoreLineSaveParam lineSaveParam : scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_0.getCode())) {
                    sngleScoreLineItems.addAll(lineSaveParam.getScoreLineItems());
                }
                sngleScoreLineItemMap = sngleScoreLineItems.stream().collect(Collectors.groupingBy(c -> c.getSubjectId()));
            }


        }
        return sngleScoreLineItemMap;
    }


    @Override
    public void checkExamineeOrigin(String examId) {
        if (StringUtils.isNotEmpty(examId)) {
            ExamInfo examInfo = examInfoMapper.selectExamInfoById(examId);
            if (null == examInfo) {
                throw new CustomException("考试数据不存在");
            }
            if (StringUtils.isNotEmpty(examInfo.getOrigin()) && "1".equals(examInfo.getOrigin())) {
                throw new CustomException("云考试数据，系统暂时不能操作");
            }
        }
    }

    @Override
    public void checkExamineeArchived(String examId) {
        int examineeCount = 0;
        Map<String, Object> parms = new HashMap<>();
        parms.put("relationId", examId);
        List<ExamInfoVo> examInfoVos = new ArrayList<>();
        if (examId != null) {
            examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
        }
        if (CollectionUtils.isNotEmpty(examInfoVos)) {
            ExamInfo examInfo = examInfoMapper.selectExamInfoById(examId);
            if (ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examInfo.getExamForm())
                    && CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
                for (ExamInfoVo examInfoVo : examInfoVos) {
                    examineeCount += enterpriseExamineeInfoMapper.countArchivedExaminee(examInfoVo.getId());
                }
            }
        } else {
            examineeCount = enterpriseExamineeInfoMapper.countArchivedExaminee(examId);
        }

        // 科目归档暂不做最终判定条件，总成绩归档才算归档
        // Integer subjectCount = enterpriseExamineeSubjectGradeMapper.countArchivedExamineeSubject(examId);
        if (examineeCount > 0) {
            throw new CustomException("该场考试已存在归档考生，不允许修改！");
        }
    }


    /**
     * 分页查询企业招聘考生复核信息列表
     *
     * @param queryExamineeGradeVo
     * @return
     */
    @Override
    public PageInfo<List<ExamReviewInfoVo>> selectReviewEnterpriseExamineeGradePage(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) {
        // 默认查询最后一场考试考生
        if (StringUtils.isEmpty(queryExamineeGradeVo.getExamId())) {
            return new PageInfo(Collections.emptyList());
        }
        queryExamineeGradeVo.setOfficeId(iBaseLoginService.getOfficeId());
        PageHelper.startPage(queryExamineeGradeVo.getPageNum(), queryExamineeGradeVo.getPageSize());
        List<ExamReviewInfoVo> examReviewInfoVos = enterpriseExamineeInfoMapper.selectReviewEnterpriseExamineeGradePage(queryExamineeGradeVo);
        return new PageInfo(examReviewInfoVos);


    }

    @Override
    public Integer cancelEnterpriseExamineeArchive(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) throws Exception {
        if (StringUtils.isEmpty(queryExamineeGradeVo.getExamId())) {
            throw new CustomException("考试ID不能为空！");
        }
        //考试组归档
        // 判断考试是否存在
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(queryExamineeGradeVo.getExamId());
        if (examInfo == null || StringUtils.isEmpty(examInfo.getExamNameConfigId())) {
            throw new CustomException("所选考试不存在！");
        }
        if (null == queryExamineeGradeVo.getExamineeIds() || queryExamineeGradeVo.getExamineeIds().length < 1) {
            throw new CustomException("考生ID不能为空！");
        }

        // 查询考试是否关联证书
        ZsInfoVO zsInfoVO = zsInfoService.getZsInfoByDataSourceToExam(queryExamineeGradeVo.getExamId());
        if (null != zsInfoVO) {
            // 证书是否发布
            if (CertificateStatusEnums.PUBLISHED.getCode().equals(zsInfoVO.getCertificateStatus())) {
                throw new CustomException("证书已发布，不允许进行取消归档操作！");
            }
        }

        // 查询考试是否关联证书
        Boolean relationZs = Boolean.FALSE;
        // 查询关联证书的列表
        List<ZsInfoVO> zsInfoVOS = zsInfoService.listZsInfoByDataSourceToExam(queryExamineeGradeVo.getExamId());
        if (CollUtil.isNotEmpty(zsInfoVOS)) {
            relationZs = Boolean.TRUE;
            List<EnterpriseExamineeInfo> enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryExamineeGradeVo.getExamineeIds()));
            if (CollectionUtils.isNotEmpty(enterpriseExamineeInfo)) {
                for (ZsInfoVO infoVO : zsInfoVOS) {
                    for (EnterpriseExamineeInfo enterpriseExamineeInfo2 : enterpriseExamineeInfo) {
                        ZsExamineeInfo zsExamineeInfo = zsExamineeInfoMapper.getZsExamineeInfoByAdmissionNo(infoVO.getId(), enterpriseExamineeInfo2.getName(), enterpriseExamineeInfo2.getAdmissionNo(), enterpriseExamineeInfo2.getIdcard());
                        if (null != zsExamineeInfo && null != zsExamineeInfo.getCertificateProvideStatus() && CertificateProvideStatusEnums.PROVIDED.getCode().equals(zsExamineeInfo.getCertificateProvideStatus())) {
                            throw new CustomException("证书已发放，不允许取消归档！");
                        }
                    }
                }

            }
        }

        if ("1".equals(queryExamineeGradeVo.getTickFlag())) {
            //归档总成绩
            if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {
                if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
                    Map<String, Object> parms = new HashMap<>();
                    parms.put("relationId", queryExamineeGradeVo.getExamId());
                    List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
                    for (ExamInfoVo examInfoVo : examInfoVos) {
                        enterpriseExamineeInfoMapper.updateGroupArchiveByExamId(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), examInfoVo.getId());

                    }
                    String[] examIds = examInfoVos.stream().map(e -> e.getId()).collect(Collectors.toSet()).toArray(new String[examInfoVos.size()]);
                    List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds);
                    for (ExamSubjectVo examSubjectVo : examSubjectVos) {
                        enterpriseExamineeSubjectGradeMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), examSubjectVo.getExamInfoId(), examSubjectVo.getSubjectId());

                    }

                } else {
                    enterpriseExamineeInfoMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId());
                    enterpriseExamineeSubjectGradeMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());

                }

            } else {//归档科目成绩
                enterpriseExamineeSubjectGradeMapper.updateArchiveByExamId(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId());
            }
            return 1;
        }
        if (null == queryExamineeGradeVo.getExamineeIds() || queryExamineeGradeVo.getExamineeIds().length < 1) {
            throw new CustomException("考生ID不能为空！");
        }

        //归档总成绩
        if (StringUtils.isEmpty(queryExamineeGradeVo.getSubjectId())) {

            //考数组合并考试
            if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
                Map<String, Object> parms = new HashMap<>();
                parms.put("relationId", queryExamineeGradeVo.getExamId());
                List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
                String[] examIds = examInfoVos.stream().map(e -> e.getId()).collect(Collectors.toSet()).toArray(new String[examInfoVos.size()]);
                List<EnterpriseExamineeInfo> enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryExamineeGradeVo.getExamineeIds()));
                //查询考试组另外考试的学生
                QueryEnterpriseExamineeGradeVo queryExaminee = new QueryEnterpriseExamineeGradeVo();
                queryExaminee.setExamIds(examIds);
                queryExaminee.setIdCards(enterpriseExamineeInfo.stream().filter(e -> StringUtils.isNotEmpty(e.getIdcard())).map(e -> e.getIdcard()).collect(Collectors.toSet()).toArray(new String[enterpriseExamineeInfo.size()]));
                queryExaminee.setExamineeNames(enterpriseExamineeInfo.stream().filter(e -> StringUtils.isNotEmpty(e.getName())).map(e -> e.getName()).collect(Collectors.toSet()).toArray(new String[enterpriseExamineeInfo.size()]));
                List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectExamineeExamList(queryExaminee);
                Set<String> examineeIds = enterpriseExamineeInfos.stream().map(e -> e.getId()).collect(Collectors.toSet());
                enterpriseExamineeInfoMapper.updateGroupArchiveByIds(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), examineeIds.toArray(new String[examineeIds.size()]));
                List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds);
                for (ExamSubjectVo examSubjectVo : examSubjectVos) {
                    enterpriseExamineeSubjectGradeMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), examSubjectVo.getExamInfoId(), examSubjectVo.getSubjectId(), examineeIds.toArray(new String[examineeIds.size()]));

                }
            } else {
                enterpriseExamineeInfoMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), queryExamineeGradeVo.getExamineeIds());
                enterpriseExamineeSubjectGradeMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId(), queryExamineeGradeVo.getExamineeIds());

            }
        } else {//归档科目成绩
            enterpriseExamineeSubjectGradeMapper.updateArchiveByIds(Constants.ARCHIVED_STATUS_N, DateUtils.getNowDate(), queryExamineeGradeVo.getExamId(), queryExamineeGradeVo.getSubjectId(), queryExamineeGradeVo.getExamineeIds());
        }
        // 如果考试已经关联证书
        if (relationZs) {
            for (ZsInfoVO infoVO : zsInfoVOS) {
                // 证书授予对象
                Integer certificateGrantObject = infoVO.getCertificateGrantObject();
                // 全部已归档考生
                if (null != certificateGrantObject && CertificateGrantObjectEnums.ARCHIVED.getCode().equals(certificateGrantObject)) {
                    cancelArchiveZsexamineeInfo(queryExamineeGradeVo, infoVO);
                }
                if (null != certificateGrantObject && CertificateGrantObjectEnums.EXAM_GRADE.getCode().equals(certificateGrantObject)) {
                    cancelArchiveZsexamineeInfo(queryExamineeGradeVo, infoVO, infoVO.getExamScoreLines());
                }
            }
        }
        return 1;
    }

    @Override
    public List<EnterpriseExamineeInfoVo> selectGroupEnterpriseExamineeGradePage(QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) {
        return enterpriseExamineeInfoMapper.selectGroupEnterpriseExamineeGradePage(queryExamineeGradeVo);
    }


    @Override
    public EnterpriseExamineeInfo getLastExamineeInfoByExamId(String examId) {
        return enterpriseExamineeInfoMapper.getLastExamineeInfoByExamId(examId);
    }


    @Override
    public List<EnterpriseExamineeInfo> selectEnterpriseExamineeInfoByIds(List<String> ids) {
        return enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoByIds(ids);
    }

    @Override
    public List<EnterpriseExamineeInfo> getExamineeInfoByIdentificationNo(String examId, String identificationNo) {
        return this.lambdaQuery()
                .eq(EnterpriseExamineeInfo::getExamId, examId)
                .eq(EnterpriseExamineeInfo::getIdcard, identificationNo)
                .list();
    }
}
